package com.countertack.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.security.KeyStore;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;

import org.apache.http.HttpVersion;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.NTCredentials;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

public class HttpClientUtils {
	public static String composePutRequest(String url, String postData) throws Exception{

		// HttpHttpClientFactory.createConnection("http", "10.150.100.243",
		// 9090, "admin", "admin", null);
		// CloseableHttpClient client = HttpClients.createDefault();
		CloseableHttpClient client = getHttpClient();

		 CredentialsProvider credsProvider = new BasicCredentialsProvider();
	        credsProvider.setCredentials(AuthScope.ANY,
	                new NTCredentials("admin", "admin",null,null));

	       

	        // Make sure the same context is used to execute logically related requests
	        HttpClientContext context = HttpClientContext.create();
	        context.setCredentialsProvider(credsProvider);
		// client.setCredentialsProvider(credsProvider);
		HttpPut put = new HttpPut(url);

		System.out.println("url>>>>" + url);
		put.setHeader("Content-Type", "application/json");
		//put.setHeader("Authorization", "Basic YWRtaW46YWRtaW4=");
		// g.setHeader("Username", "admin");
		// g.setHeader("Password","admin");
		CloseableHttpResponse res = null;
		try {

			StringEntity entity = new StringEntity(postData);
			
			//System.out.println("put data >>>>"+postData);
			
			put.setEntity(entity);// HttpGet g=new
									// HttpGet("http://10.150.100.243:9090/api/v1/groups");
			res = client.execute(put,context);
			//System.out.println("status code>>>>"
			//		+ res.getStatusLine().getStatusCode());

			BufferedReader read = new BufferedReader(new InputStreamReader(res
					.getEntity().getContent()));
			StringBuffer buf = new StringBuffer();
			String s = "";

			while ((s = read.readLine()) != null) {

				buf.append(s);
			}

		//	System.out.println("response>>>>>" + buf.toString());

		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// e.printStackTrace();
		} finally {

			try {
				EntityUtils.consume(res.getEntity());
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		return null;

	}

	
	public static String composePostRequest(String url, String postData) throws Exception {

		// HttpHttpClientFactory.createConnection("http", "10.150.100.243",
		// 9090, "admin", "admin", null);
		// CloseableHttpClient client = HttpClients.createDefault();
		CloseableHttpClient client = getHttpClient();

		CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(AuthScope.ANY,
                new NTCredentials("admin", "admin",null,null));

       

        // Make sure the same context is used to execute logically related requests
        HttpClientContext context = HttpClientContext.create();
        context.setCredentialsProvider(credsProvider);
		// client.setCredentialsProvider(credsProvider);
		HttpPost post = new HttpPost(url);

		//System.out.println("url>>>>" + url);
		post.setHeader("Content-Type", "application/json");
		post.setHeader("Authorization", "Basic YWRtaW46YWRtaW4=");
		// g.setHeader("Username", "admin");
		// g.setHeader("Password","admin");
		CloseableHttpResponse res = null;
		try {

			StringEntity entity = new StringEntity(postData);
			post.setEntity(entity);// HttpGet g=new
									// HttpGet("http://10.150.100.243:9090/api/v1/groups");
			res = client.execute(post,context);
			//System.out.println("status code>>>>"
			//		+ res.getStatusLine().getStatusCode());

			BufferedReader read = new BufferedReader(new InputStreamReader(res
					.getEntity().getContent()));
			StringBuffer buf = new StringBuffer();
			String s = "";

			while ((s = read.readLine()) != null) {

				buf.append(s);
			}

			//System.out.println("response>>>>>" + buf.toString());
			
			
			return buf.toString();

		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// e.printStackTrace();
		} finally {

			try {
				EntityUtils.consume(res.getEntity());
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		return null;

	}

	public static String get(String url) throws Exception {

		CloseableHttpClient client = getHttpClient();
		HttpGet get = new HttpGet(url);
		 CredentialsProvider credsProvider = new BasicCredentialsProvider();
	        credsProvider.setCredentials(AuthScope.ANY,
	                new NTCredentials("admin", "admin",null,null));

	       

	        // Make sure the same context is used to execute logically related requests
	        HttpClientContext context = HttpClientContext.create();
	        context.setCredentialsProvider(credsProvider);
		//System.out.println("url>>>>" + url);

		CloseableHttpResponse res = null;
		try {

			res = client.execute(get,context);
			//System.out.println("status code>>>>"
			//		+ res.getStatusLine().getStatusCode());

			BufferedReader read = new BufferedReader(new InputStreamReader(res
					.getEntity().getContent()));
			StringBuffer buf = new StringBuffer();
			String s = "";

			while ((s = read.readLine()) != null) {

				buf.append(s);
			}

			//System.out.println("response>>>>>" + buf.toString());
			return buf.toString();

		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// e.printStackTrace();
		} finally {

			try {
				EntityUtils.consume(res.getEntity());
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		return null;

	}

	
	public static String httpGet(String url) throws Exception {

		CloseableHttpClient client = getHttpClient();
		HttpGet get = new HttpGet(url);
		
	       

	        // Make sure the same context is used to execute logically related requests
	    
		//System.out.println("url>>>>" + url);

		CloseableHttpResponse res = null;
		try {

			res = client.execute(get);
		//	System.out.println("status code>>>>"
			//		+ res.getStatusLine().getStatusCode());

			BufferedReader read = new BufferedReader(new InputStreamReader(res
					.getEntity().getContent()));
			StringBuffer buf = new StringBuffer();
			String s = "";

			while ((s = read.readLine()) != null) {

				buf.append(s);
			}

			//System.out.println("response>>>>>" + buf.toString());
			return buf.toString();

		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// e.printStackTrace();
		} finally {

			try {
				EntityUtils.consume(res.getEntity());
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		return null;

	}

	
	
	
	public static String composegetRequest(String url) throws Exception{

		url = "https://s17.dev.countertack.com:9090/api/v1/groups";

		// HttpHttpClientFactory.createConnection("http", "10.150.100.243",
		// 9090, "admin", "admin", null);
		// CloseableHttpClient client = HttpClients.createDefault();
		CloseableHttpClient client = getHttpClient();

	     CredentialsProvider credsProvider = new BasicCredentialsProvider();
	        credsProvider.setCredentials(AuthScope.ANY,
	                new NTCredentials("admin", "admin",null,null));

	       

	        // Make sure the same context is used to execute logically related requests
	        HttpClientContext context = HttpClientContext.create();
	        context.setCredentialsProvider(credsProvider);
		HttpGet get = new HttpGet(url);
		//get.setHeader("X-Prevent-Browser-Auth" ,"true");
		// HttpPost post = new HttpPost(url);

		System.out.println("url>>>>" + url);
		// post.setHeader("Content-Type", "application/json");
		// post.setHeader("Authorization","Basic YWRtaW46YWRtaW4=");
		// g.setHeader("Username", "admin");
		// g.setHeader("Password","admin");
		CloseableHttpResponse res = null;
		try {

			// StringEntity entity = new StringEntity(postData);
			// post.setEntity(entity);// HttpGet g=new
			// // HttpGet("http://10.150.100.243:9090/api/v1/groups");
			res = client.execute(get,context);
			System.out.println("status code>>>>"
					+ res.getStatusLine().getStatusCode());

			BufferedReader read = new BufferedReader(new InputStreamReader(res
					.getEntity().getContent()));
			StringBuffer buf = new StringBuffer();
			String s = "";

			while ((s = read.readLine()) != null) {

				buf.append(s);
			}

			System.out.println("response>>>>>" + buf.toString());

		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// e.printStackTrace();
		} finally {

			try {
				EntityUtils.consume(res.getEntity());
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		return null;

	}

//	public static DefaultHttpClient getNewHttpClient() {
//		try {
//			KeyStore trustStore = KeyStore.getInstance(KeyStore
//					.getDefaultType());
//
//		 File f=new File("C:\\Users\\user\\Desktop\\truststore.jks");
//			//trustStore.load(null, null);
//			trustStore.load(new FileInputStream(f),
//			 "countertack".toCharArray());
//			SSLSocketFactory sf = new MySSLSocketFactory(trustStore);
//			sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
//
//			HttpParams params = new BasicHttpParams();
//			HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
//			HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
//
//			SchemeRegistry registry = new SchemeRegistry();
//			registry.register(new Scheme("http", PlainSocketFactory
//					.getSocketFactory(), 80));
//			registry.register(new Scheme("https", sf, 443));
//
//			ClientConnectionManager ccm = new ThreadSafeClientConnManager(
//					params, registry);
//
//			return new DefaultHttpClient(ccm, params);
//		} catch (Exception e) {
//			return new DefaultHttpClient();
//		}
//	}
//
//	public static void main(String[] args) throws Exception {
//		System.setProperty("javax.net.debug", "ssl"); 
//		composegetRequest(null);
//		
//		
//	}

  
	public static void main(String[] args)throws Exception{
		 String configFilePath =
				 "config.properties";

				Configuration.loadProperties(configFilePath);
		
		composegetRequest(null);
//			String res=	composePostRequest("https://:9090/api/v1/search/raw", "{\"query\": \"select name from endpoints\"}");
//			System.out.println(res);
		
	}
	public static CloseableHttpClient getHttpClient() throws Exception{
		
		
		
	    KeyStore trustStore  = KeyStore.getInstance(KeyStore.getDefaultType());
	    String keyStorePath=Configuration.getProperty("keystorepath");
	  FileInputStream instream = new FileInputStream(new File(keyStorePath));
	  try {
	      trustStore.load(instream, "countertack".toCharArray());
	  } finally {
	      instream.close();
	  }

	  // Trust own CA and all self-signed certs
	  SSLContext sslcontext = SSLContexts.custom()
	          .loadTrustMaterial(trustStore, new TrustSelfSignedStrategy())
	          .build();
	  // Allow TLSv1 protocol only
	  SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
	          sslcontext,
	          new String[] { "TLSv1" },
	          null,
	          SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
	  CloseableHttpClient httpclient = HttpClients.custom()
	  	
	          .setSSLSocketFactory(sslsf)
	          .build();
		return httpclient;
		
	}
}
